//
//  CityListViewController.swift
//  MyWeatherApp
//
//  Created by Shengbing Li (QXU7859) on 2021/2/27.
//  Copyright © 2021 shanghai. All rights reserved.
//

import UIKit
import ObjectMapper

class CityListViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    var city: QueryType?
    
    private lazy var array: [LocationSearchModel] = [LocationSearchModel]()
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "城市天气"
        
        updateUI()
        loadCityData()
    }
    
    private func updateUI() {
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellIndentifier")
        tableView.tableFooterView = UIView()
    }
    
    private func loadCityData() {
        HudView.share.beginHud(T: view)
        let locationSearchRequest = LocationSearchRequest(query: self.city ?? QueryType.query("Shanghai"))
        API.current()?.fetch(locationSearchRequest, complete: { (response) in
            HudView.share.HideHud()
            guard let result = response.raw?.arrayValue else { return }
            for json in result {
                guard let model = Mapper<LocationSearchModel>().map(JSON: json.dictionaryObject ?? [:]) else { break }
                self.array.append(model)
            }
            self.tableView.reloadData()
        })
    }

}

extension CityListViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellIndentifier", for: indexPath)
        cell.textLabel?.text = self.array[indexPath.row].title ?? ""
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let weatherListVc = WeatherListViewController()
        weatherListVc.woeid = self.array[indexPath.row].woeid
        navigationController?.pushViewController(weatherListVc, animated: true)
    }
}
